<template>
  <div class="container">
    <div class="header">
      <h2>{{ headerTitle }}</h2>
      <div>
        <el-button
          type="primary"
          @click="
            showAddDialog = true;
            isEditMode = false;
          "
          >新增</el-button
        >
        <el-button type="success" @click="showSearchDialog = true"
          >查找</el-button
        >
      </div>
    </div>

    <div class="table-container">
      <div class="table-wrapper">
        <el-table :data="list" border stripe style="width: 100%; height: 60vh">
          <el-table-column
            v-for="(label, prop) in formPropMap"
            :key="prop"
            :prop="prop"
            :label="label"
          />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button @click="handleUpdate(scope.row.deptId)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                @click="handleDelete(scope.row.deptId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="params.page"
            v-model:page-size="params.size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- // TODO: 查询功能暂未实现 -->
      <!-- 查找学院 -->
      <el-dialog v-model="showSearchDialog" width="30%" title="查找学院">
        <el-form :model="updateForm" label-width="15%">
          <el-form-item label="学院id">
            <el-input v-model="updateForm.deptId" placeholder="请输入学院id" />
          </el-form-item>
          <el-form-item label="学院名">
            <el-input
              v-model="updateForm.deptName"
              placeholder="请输入学院名"
            />
          </el-form-item>
          <el-form-item label="地址">
            <el-input
              v-model="updateForm.deptLocation"
              placeholder="请输入地址"
            />
          </el-form-item>
          <el-form-item label="院系主任电话">
            <el-input
              v-model="updateForm.deptPhone"
              placeholder="请输入院系主任电话"
            />
          </el-form-item>
          <el-form-item label="院系主任名">
            <el-input
              v-model="updateForm.deanName"
              placeholder="请输入院系主任名"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="btn-group">
            <el-button @click="showSearchDialog = false">取消</el-button>
            <el-button type="primary" @click="handleSearch">查找</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 修改/添加学院 -->
      <el-dialog
        v-model="showAddDialog"
        :title="isEditMode ? '修改学院信息' : '添加学院'"
        width="30%"
        @close="handleAddDialogClose"
      >
        <el-form :model="updateForm" label-width="30%">
          <el-form-item label="学院id">
            <el-input v-model="updateForm.deptId" placeholder="请输入学院id" />
          </el-form-item>
          <el-form-item label="学院名">
            <el-input
              v-model="updateForm.deptName"
              placeholder="请输入学院名"
            />
          </el-form-item>
          <el-form-item label="地址">
            <el-input
              v-model="updateForm.deptLocation"
              placeholder="请输入地址"
            />
          </el-form-item>
          <el-form-item label="院系主任电话">
            <el-input
              v-model="updateForm.deptPhone"
              placeholder="请输入院系主任电话"
            />
          </el-form-item>
          <el-form-item label="院系主任名">
            <el-input
              v-model="updateForm.deanName"
              placeholder="请输入院系主任名"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="btn-group">
            <el-button
              @click="
                showAddDialog = false;
                isEditMode = false;
              "
              >取消</el-button
            >
            <el-button v-if="isEditMode" type="primary" @click="update"
              >修改</el-button
            >
            <el-button v-else type="primary" @click="handleAdd">添加</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="showDeleteDialog" title="删除学院" width="30%">
        <span>确定要删除学院 {{ deleteId }} 吗？</span>
        <template #footer>
          <el-button
            @click="
              showDeleteDialog = false;
              deleteId = defaultDeleteIdValue;
            "
            >取消</el-button
          >
          <el-button type="danger" @click="deleteDepartment">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { departmentApi } from "@/api";
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref } from "vue";

/**
 *           .__                                     __
 *      ____ |  |__ _____    ____    ____   ____   _/  |_  ____    ___.__. ____  __ _________  ___  _______ _______  ______
 *    _/ ___\|  |  \\__  \  /    \  / ___\_/ __ \  \   __\/  _ \  <   |  |/  _ \|  |  \_  __ \ \  \/ /\__  \\_  __ \/  ___/
 *    \  \___|   Y  \/ __ \|   |  \/ /_/  >  ___/   |  | (  <_> )  \___  (  <_> )  |  /|  | \/  \   /  / __ \|  | \/\___ \
 *     \___  >___|  (____  /___|  /\___  / \___  >  |__|  \____/   / ____|\____/|____/ |__|      \_/  (____  /__|  /____  >
 *         \/     \/     \/     \//_____/      \/                  \/                                      \/           \/
 */

/**
 * 全局替换下面的文字成当前页面的名字：
 *
 * 学院
 * department
 * Department
 *
 */

// 页面标题
const headerTitle = ref("院系管理");

const defaultIdValue = 0;
const defaultEditIdValue = 0;
const defaultDeleteIdValue = 0;

type IdType = number;

const defaultForm = {
  deptId: defaultIdValue,
  deptName: "",
  deptLocation: "",
  deptPhone: "",
  deanName: ""
};

/**
 * 属性名称映射表
 */
const formPropMap = {
  deptId: "学院号",
  deptName: "学院名",
  deptLocation: "地址",
  deptPhone: "学院电话",
  deanName: "院系主任电话"
};

type DepartmentForm = {
  deptId: IdType;
  deptName: string;
  deptLocation: string;
  deptPhone: string;
  deanName: string;
};

// 更新、添加、查找三用表单
const updateForm = reactive<DepartmentForm>({
  deptId: 0,
  deptName: "",
  deptLocation: "",
  deptPhone: "",
  deanName: ""
});

const showAddDialog = ref(false);
const showSearchDialog = ref(false);

// 分页相关
interface PageParams {
  page: number;
  size: number;
}

// 表格
const list = ref<DepartmentForm[]>([]);
// 数据总数
const total = ref(0);
// 分页请求参数
const params = ref<PageParams>({
  page: 1,
  size: 10
});

// 更新学院id
const editId = ref<IdType>(defaultEditIdValue);
// 编辑模式状态
const isEditMode = ref(false);

const resetUpdateForm = () => {
  Object.assign(updateForm, defaultForm);
};

const handleAddDialogClose = () => {
  resetUpdateForm();
};

/**
 * 处理更新
 * @param id 学院id
 */
const handleUpdate = async (id: IdType) => {
  try {
    // 切换到编辑模式
    isEditMode.value = true;
    // 更新需要修改的学院id
    editId.value = id;
    // 获取该学院信息
    const department = await departmentApi.getById(id);
    // 填写信息到表单
    Object.assign(updateForm, department.data);
    // 打开修改弹窗
    showAddDialog.value = true;
  } catch (error) {
    ElMessage.error("学院获取失败");
    console.error("学院获取失败：", error);
  }
};

/**
 * 更新学院
 */
const update = async () => {
  try {
    await departmentApi.update(editId.value, updateForm);
    ElMessage.success("学院更新成功");
  } catch (error) {
    ElMessage.error("学院更新失败");
    console.error("学院更新失败：", error);
  } finally {
    // 重置表单
    Object.assign(updateForm, defaultForm);
    // 关闭更新窗口
    showAddDialog.value = false;
    // 重置编辑id
    editId.value = defaultEditIdValue;
    // 关闭编辑模式
    isEditMode.value = false;
    // 刷新
    getList();
  }
};

/**
 * 新增学院
 */
const handleAdd = async () => {
  try {
    // 发送请求
    await departmentApi.create(updateForm);
    ElMessage.success("添加成功");
  } catch (error) {
    ElMessage.error("添加失败");
    console.error("删除失败：", error);
  } finally {
    // 关闭新增窗口
    showAddDialog.value = false;
    // 置空新增表单信息
    Object.assign(updateForm, defaultForm);
    // 刷新
    getList();
  }
};

const showDeleteDialog = ref(false);
// 需要删除的学院id
const deleteId = ref(defaultDeleteIdValue);

const handleDelete = async (id: IdType) => {
  deleteId.value = id;
  // 打开删除弹窗
  showDeleteDialog.value = true;
};

/**
 * 删除学院
 */
const deleteDepartment = async () => {
  try {
    if (!deleteId.value) {
      throw new Error("无效删除信息");
    }

    // 发出删除申请
    await departmentApi.delete(deleteId.value);
    ElMessage.success("删除成功");
  } catch (error) {
    ElMessage.error("删除失败");
    console.error("删除失败：", error);
  } finally {
    // 关闭删除弹窗
    showDeleteDialog.value = false;
    // 重置删除id，防止误删
    deleteId.value = defaultDeleteIdValue;
    // 刷新
    getList();
  }
};

const handleSearch = async () => {
  try {
  } catch (error) {
    ElMessage.error("查找失败");
    console.error("查找失败：", error);
  } finally {
  }
};

/**
 * 处理每页大小变化
 * @param val 每页大小
 */
const handleSizeChange = (val: number) => {
  params.value.size = val;
  params.value.page = 1;
  getList();
};

/**
 * 处理页面切换
 * @param val 页号
 */
const handleCurrentChange = (val: number) => {
  params.value.page = val;
  getList();
};

/**
 * 获取表格
 */
const getList = async () => {
  try {
    const res = await departmentApi.getPage({
      page: params.value.page - 1,
      size: params.value.size
    });
    list.value = res.data.content || [];
    total.value = res.data.totalElements || 0;
  } catch (error) {
    ElMessage.error("表格获取失败");
    console.error("表格获取失败：", error);
  }
};

onMounted(async () => {
  await getList();
});
</script>

<style lang="css">
.container {
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  height: 80vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-shrink: 0;

  h2 {
    margin: 0;
    color: #303133;
  }
}

.table-container {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  overflow-y: auto;
}

.pagination {
  flex-shrink: 0;
  background: white;
  padding: 10px 0;
}

.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
